package com.murong.ai.chat.infrastructure.httprequest;

import com.google.gson.Gson;
import com.murong.ai.chat.infrastructure.httprequest.module.HttpHeader;
import lombok.SneakyThrows;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

public abstract class HttpClientService <ReqDTO,RspDTO>{

    public void beforeProcess(ReqDTO opRequest){

    }

    @SneakyThrows
    public RspDTO request(ReqDTO opRequest) {

        // 前置处理
        beforeProcess(opRequest);

        // 构建 POST 请求
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest.Builder httpBuilder = HttpRequest
                .newBuilder().uri(URI.create(getUri())).header("Content-Type", "application/json");
        List<HttpHeader> httpHeaders = getheaderList();

        if(httpHeaders!=null) {
            for(HttpHeader header:httpHeaders) {
                httpBuilder=httpBuilder.header(header.getName(),header.getValue());
            }
        }

        HttpRequest request = httpBuilder.POST(buildRequestBody(opRequest)).build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if(response.statusCode()==200) {
           return buildResponseBody(response);
        }else {
            throw new RuntimeException("Response Error code:["+response.statusCode()+"]");
        }
    }

    public HttpRequest.BodyPublisher buildRequestBody(ReqDTO opRequest) {
        if(opRequest instanceof String) {
            return HttpRequest.BodyPublishers.ofString((String)opRequest);
        }else {
            Gson gson = new Gson();
            String json = gson.toJson(opRequest);
            return HttpRequest.BodyPublishers.ofString(json);
        }
    }

    public abstract RspDTO buildResponseBody(HttpResponse<String> response);

    public abstract String getUri();

    public List<HttpHeader> getheaderList() {
        return null;
    }
}
